# -*- coding: utf-8 -*-
# @Time    : 2024/5/22 8:43 下午
# @Author  : Hoey

from pymysql import Connection

from day04.加载资源 import get_mysql_config


class MysqlUtil():

    def __init__(self
                 , xhost
                 , xport
                 , xuser
                 , xpassword
                 , xdatabase):
        self.host = xhost
        self.port = xport
        self.user = xuser
        self.password = xpassword
        self.database = xdatabase
        self.conn = Connection(
            host=self.host
            , port=xport
            , user=self.user
            , password=xpassword
            , database=self.database
        )

    # 查找
    def select(self):
        cur = self.conn.cursor()
        cur.execute('select * from test1;')
        result = cur.fetchall()
        print(f"结果: {result}, 类型: {type(result)}")
        cur.close()

    def create(self):
        cur = self.conn.cursor()
        sql = """
            create table test2(
                id int,
                name varchar(255)
            );
            """
        cur.execute(sql)
        cur.close()

    # 插入数据
    def insert(self):
        cur = self.conn.cursor()
        sql = """
            insert into test2(id, name) values(1, 'maodandan')
        """
        cur.execute(sql)
        self.conn.commit()
        cur.close()

    # 更新maodandan -> maodandan1
    def update(self):
        cur = self.conn.cursor()
        sql = """
        update test2 set name = 'maodandan2' where name = 'maodandan'
        """
        cur.execute(sql)
        self.conn.commit()
        cur.close()

    # 拓展缺少的功能


if __name__ == '__main__':
    db = MysqlUtil(
        xhost=get_mysql_config('mysql-ceshi','host'),
        xport=int(get_mysql_config('mysql-ceshi','port')),
        xuser=get_mysql_config('mysql-ceshi','user'),
        xpassword=get_mysql_config('mysql-ceshi','password'),
        xdatabase=get_mysql_config('mysql-ceshi','database')
    )
    db.select()